package cn.wolfcode.shop.cloud.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class ErrorResponseJSONFilter extends ZuulFilter {
    @Value("${error.path:/error}")
    private String errorPath;

    public ErrorResponseJSONFilter() {
    }

    public String filterType() {
        return "error";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable() != null && !ctx.getBoolean("sendErrorFilter.ran", false);
    }

    @Override
    public Object run() throws ZuulException {
        HashMap<String, Object> data = new HashMap<>();
        //获取响应对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        //设置响应类型为json类型
        response.setContentType("text/json;charset=utf-8");
        if ("true".equals(ctx.get("rateLimitExceeded"))){
            data.put("code",429);
            data.put("msg","操作过于频繁，请稍后再试");
        }else {
            data.put("code",500);
            data.put("msg","系统繁忙");
        }
        //把数据响应到浏览器
        try {
            response.getWriter().write(JSON.toJSONString(data));

        } catch (IOException e) {
            e.printStackTrace();
        } //这个filter没过，后面的filter也不用走了
        ctx.setSendZuulResponse(false);

        return null;
    }


}
